/*
* FaceCat图形通讯框架
* 著作权编号:2015SR229355+2020SR0266727
* 上海卷卷猫信息技术有限公司
*/

package facecat.topin.sock;

import java.util.*;

/*
* 客户端套接字连接管理
*/
public class FCClientSockets {
    private static HashMap<Integer, FCClientSocket> m_clients = new HashMap<Integer, FCClientSocket>();

    private static FCSocketListener m_listener;

    private static int m_socketID;

    /*
    * 关闭连接
    */
    public static int close(int socketID) {
        int ret = -1;
        synchronized(m_clients){
            if (m_clients.containsKey(socketID)) {
                FCClientSocket client = m_clients.get(socketID);
                ret = client.close();
                m_clients.remove(socketID);
            }
        }
        return ret;
    }
    
    /*
    * 连接到TCP
    */
    public static int connectTCP(String ip, int port){
        return connect(0, ip, port, "", 0, "", "", "", 6);
    }

    /*
    * 连接
    */
    public static int connect(int proxyType, String ip, int port, String proxyIp, int proxyPort, String proxyUserName, String proxyUserPwd, String proxyDomain, int timeout) {
        FCClientSocket client = new FCClientSocket((long)proxyType, ip, port, proxyIp, proxyPort, proxyUserName, proxyUserPwd, proxyDomain, timeout);
        FCClientSocket.ConnectStatus ret = client.connect();
        if (ret != FCClientSocket.ConnectStatus.CONNECT_SERVER_FAIL) {
            m_socketID++;
            Integer socketID = (Integer) m_socketID;
            client.m_hSocket = m_socketID;
            synchronized(m_clients){
                m_clients.put(socketID, client);
            }
            return socketID;
        } else {
            client.delete();
            return -1;
        }
    }

    /*
    * 连接客户端消息
    */
    public static void recvClientMsg(int socketID, int localSID, byte[] str, int len) {
        m_listener.callBack(socketID, localSID, str, len);
    }

    /*
    * 发送消息
    */
    public static int send(int socketID, byte[] str, int len) {
        int ret = -1;
        synchronized(m_clients){
            if (m_clients.containsKey(socketID)) {
                FCClientSocket client = m_clients.get(socketID);
                ret = client.send(str, len);
            }
        }
        return ret;
    }

    /*
    * 设置监听
    */
    public static int setListener(FCSocketListener listener) {
        m_listener = listener;
        return 1;
    }

    /*
    * 写客户端日志
    */
    public static void writeClientLog(int socketID, int localSID, int state, String log) {
        m_listener.writeLog(socketID, localSID, state, log);
    }
}
